#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QStringList>
#include <QSqlRecord>
#include <vector>

using namespace std;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("Print Test");
    //SQLite数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("../test.db");
    if(!db.open())
    {
        QMessageBox::warning(this, "error", db.lastError().text());
        qDebug()<<QString("fail!!!!!!!!!");
        //return;
    }
    else
    {
        QMessageBox::information(this, "数据库", "数据库连接成功！");
        qDebug()<<QString("success!!!!!!!!!");
    }
    model = new QSqlTableModel(ui->tableView);
    model->setTable("StuInfo");//选择表
    //把model放在view里面
    ui->tableView->setModel(model);
    model->select();
    //设置model1编辑模式为手动提交修改
    //model1->setEditStrategy(QSqlTableModel::OnManualSubmit);
    //只读
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //表格宽度随内容调整
    ui->tableView->horizontalHeader()
        ->setSectionResizeMode(QHeaderView::ResizeToContents);

}

Widget::~Widget()
{
    delete ui;
}
//按下打印按钮
void Widget::on_buttonPrint_clicked()
{
    int rowNum=model->rowCount();
    QString title1=QString("Student Information");//打印表格的标题
    QStringList columnList;//columnList为各列名
    vector<QStringList> dataLists;//dataLists为各行数据
    columnList<<"name"<<"age"<<"ID";
    for(int i=0;i<rowNum;i++)
    {
        QStringList data;
        for(int j=0;j<3;j++)
        {
            data<<model->record(i).value(j).toString();
        }
        dataLists.push_back(data);
    }
    QPrinterManager PM;
    PM.dataBegin();
    PM.insertTitle(title1);
    PM.insertTitle2("blank_shen");
    PM.tableBegin(columnList);
    for(int row=0;row<rowNum;row++)
    {
        PM.insert2TableRow(dataLists[row]);
    }

    PM.tableEnd();
    PM.dataEnd();
    PM.printWithPreview();
}
